package com.docman.controller;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.docman.dao.UserDAO;
import com.docman.domainmodel.UserBean;

@WebServlet("/ChangePasswordServlet")
public class ChangePasswordServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public ChangePasswordServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding("text/html;  charset=utf-8");
		request.setCharacterEncoding("UTF-8");
		
		UserBean user = new UserBean();
		//getting required parameters to initialise UserBean object.
		String userName = request.getParameter("userName");
		String currentPassword = request.getParameter("currentPassword");
		String newPassword = request.getParameter("newPassword");
		String verifyNewPassword = request.getParameter("verifyNewPassword");
		
		
		//checking possible errors , password mismatch etc.
		if(userName != null && userName != "" ){
			user.setUserName(userName);
			
		}		
		if(currentPassword != null && currentPassword != ""){
			try {
				MessageDigest md = MessageDigest.getInstance("SHA-256");
				 md.update(currentPassword.getBytes());
				 
			        byte byteData[] = md.digest();
			 
			        //convert the byte to hex format method 1
			        StringBuffer sb = new StringBuffer();
			        for (int i = 0; i < byteData.length; i++) {
			         sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
			         currentPassword = sb.toString();
			        }
			} catch (NoSuchAlgorithmException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			user.setPassword(currentPassword);
			
		}
		if((newPassword != null && newPassword != "") && (newPassword.equals(verifyNewPassword)) ){
			try {
				MessageDigest md = MessageDigest.getInstance("SHA-256");
				 md.update(newPassword.getBytes());
				 
			        byte byteData[] = md.digest();
			 
			        //convert the byte to hex format method 1
			        StringBuffer sb = new StringBuffer();
			        for (int i = 0; i < byteData.length; i++) {
			         sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
			         newPassword = sb.toString();
			        }
			} catch (NoSuchAlgorithmException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			user.setNewPassword(newPassword);
			
		}
		
		boolean error = false;
		
		//calling DAO object to change password. If process is successful than user may login again login
		//to system. If process fails than user warned by a massage.
		try{
		UserDAO.changePassword(user);
		}
		catch (Exception e){
			System.out.println("exception in servlet "+e);
			request.setAttribute("error", "Geçerli şifrenizi yanlış girdiniz. Lütfen tekrar deneyiniz.");
			//e.printStackTrace();
			 error=true;
		}
		
		if(!error){
			request.setAttribute("error", "Şifreniz değişmiştir. Lütfen yeni şifreniz ile giriş yapınız.");
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp");
			HttpSession session = request.getSession();
			session.invalidate();
			dispatcher.forward(request, response);
		} else{
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/changePassword.jsp");
			dispatcher.forward(request, response);
		}		
		
	}

}
